package com.starblink.home.ui.part

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import com.guadou.lib_baselib.view.span.dsl.buildSpannableString
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.extraOf
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.urllink.PullUpPageUtils
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.CoroutineUpdateTask
import com.starblink.android.common.view.decoration.SpaceItemDecoration
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.view.recyclerview.SimpleGapItemDecor
import com.starblink.basic.util.ActivityStackManage
import com.starblink.home.R
import com.starblink.home.databinding.FragmentNavHomeBinding
import com.starblink.home.databinding.ItemHomeDiscountBinding
import com.starblink.home.databinding.LayoutHomeDiscountBinding
import com.starblink.home.ui.NavHomeVM
import com.starblink.home.ui.bean.TopSuperStoreBean
import com.starblink.home.ui.cells.DiscountChildCell
import com.starblink.library.widget.novice_guide.control.GuidePopStatusControl
import com.starblink.rocketreserver.DiscountMerchantsListV3Query

/**
 * 处理折扣
 */
class PartDiscountMer(
    var vb: LayoutHomeDiscountBinding,
    var parentVb: FragmentNavHomeBinding,
    var viewModel: NavHomeVM,
    var homeApiResultControl: HomeApiResultControl
) {


    private companion object {
        const val TAG = "PartDiscountMer"
    }

    /**
     * 折扣adapter
     */
    private val discountAdapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.discountAdapterData).apply {
            //类目
            addVhDelegate {
                DiscountChildCell(
                    ItemHomeDiscountBinding.inflate(it.inflater, it, false),
                    parentVb,
                    homeApiResultControl
                )
            }
        }
    }

    fun handleVM() {
        if (vb.discountRv6.adapter == null) {
            var subManager = GridLayoutManager(ActivityStackManage.currentActivity(), 3)
            vb.discountRv6.layoutManager = subManager
            vb.discountRv6.setHasFixedSize(true)
            vb.discountRv6.itemAnimator = null
            vb.discountRv6.addItemDecoration(
                SimpleGapItemDecor(horGap = 8.dp2px(), verGap = 8.dp2px(), withEdge = false)
            )
            vb.discountRv6.adapter = discountAdapter
        }



        vb.lDiscount.setOnClickListener {
//            navigationTo(
//                url = PullUpPageUtils.h5Url(
//                    "/shop-activity/sale-zone?countryCode=${UserDataCenter.getLocalCountryCode()}&merchantTop3=${viewModel.thisMerchantTop3Str}"
//                )
//            )
            navigationTo(RoutePage.SuperStoreDeal.HOME) {
                extraOf(
                    "deals" to viewModel.discountAdapterData.mapNotNull { it.data?.merchantWebVOF?.id }
                        .toTypedArray()
                )
            }
        }


        //点击viewAll
        vb.lDiscount.trackData(
            page = SpmPageDef.Home080Page_10164,
            element = SpmElementDef.ELE_33009,
            onlyHit = true
        )

        //进行引导弹窗的轮询
        GuidePopStatusControl.popDiscountGuide(
            appBar = parentVb.appBar,
            refreshLayout = parentVb.page,
            screenView = vb.inside,
            tarView = vb.inside,
            bootView = parentVb.root as ViewGroup,
            guideType = TAG
        )
    }


    //是否显示过骨架图
    private var showSkeleton = false
    fun dataChange(data: List<DiscountMerchantsListV3Query.MerchantWeb?>?) {
        GuidePopStatusControl.homeDiscountHasData = false
        if (data.isNullOrEmpty()) {
            if (!showSkeleton) {
                showSkeleton = true
                isHasDataLay(true, 6)
            } else {
                isHasDataLay(false)
            }
        } else {
            //区域单独曝光
            SpmTrackHandler.addSingleTrackData(
                SkAntEntity(
                    event = TrackEvent.elementExposure.value,
                    spmCnt = GTrackerAssistUtils.fetchElementValue(
                        page = SpmPageDef.Home080Page_10164,
                        element = SpmElementDef.ELE_33009,
                    )
                )
            )
            //如果数据小于6大于2 显示3个
            when (data.size) {
                in 3..5 -> {
                    GuidePopStatusControl.homeDiscountHasData = true
                    isHasDataLay(true, 3)
                    viewModel.discountAdapterData.clear()
                    for ((index, outletsBean) in data.withIndex()) {
                        //最多取前3
                        if (index < 3) {
                            viewModel.discountAdapterData.add(TopSuperStoreBean(index, outletsBean))
                        }
                    }
                    discountAdapter.notifyDataSetChanged()
                }

                6 -> {
                    GuidePopStatusControl.homeDiscountHasData = true
                    isHasDataLay(true, 6)
                    viewModel.discountAdapterData.clear()
                    for ((index, outletsBean) in data.withIndex()) {
                        viewModel.discountAdapterData.add(TopSuperStoreBean(index, outletsBean))
                    }
                    discountAdapter.notifyDataSetChanged()
                }

                else -> {
                    isHasDataLay(false)
                }
            }
        }

//        if (it.size > 3) {
//            vb.discountState.visible()
//            discountAdapter.notifyDataSetChanged()
//        } else {
//            if (viewModel.allApiCompleted.value!![ApiReqStatusEnum.DISCOUNT_MERCHANTS] == true) {
//                vb.discountState.gone()
//            }
//        }
    }

    @SuppressLint("SetTextI18n")
    private fun isHasDataLay(hasData: Boolean, size: Int = 0) {
        if (hasData) {
            if (viewModel.discountStoreNum > 0) {
                vb.discountTitleText.text = "${viewModel.discountStoreNum} "
                vb.discountTitleTextSuffix.visible()
            } else {
                vb.discountTitleTextSuffix.gone()
            }
            if (size == 3) {
                vb.inside.setBackgroundResource(R.mipmap.home_discount_bg_3)
            } else {
                vb.inside.setBackgroundResource(R.mipmap.home_discount_bg_6)
            }
            vb.inside.visible()
            vb.discountTitle.visible()
            vb.discountRv6.visible()
            vb.discountNoData.gone()
        } else {
            vb.inside.setBackgroundResource(com.starblink.basic.style.R.color.transparent)
            vb.discountTitle.gone()
            vb.discountRv6.gone()
            if (viewModel.bannerObserveData.value.isNullOrEmpty()) {
                vb.discountNoData.visible()
            } else {
                vb.inside.gone()
            }
        }
    }
}